package com.itwill.ecom.board;

import java.io.File;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.itwill.ecom.boardReply.BoardReplyBeans;
import com.itwill.ecom.boardReply.BoardReplyServiceImpl;
import com.itwill.ecom.boardType.BoardTypeBeans;
import com.itwill.ecom.boardType.BoardTypeService;
import com.itwill.ecom.member.MemberBeans;
import com.itwill.ecom.member.MemberServiceImpl;

@Controller
@RequestMapping("/board")
public class BoardController {
	@Autowired
	private BoardServiceImpl boardService;
	@Autowired
	private MemberServiceImpl memberService;
	@Autowired
	private BoardReplyServiceImpl boardReplyService;
	@Autowired
	private BoardTypeService boardTypeService;

	public BoardController() {
		System.out.println("### BoardController 생성자 ###");
	}

	@RequestMapping(value = "/boardwrite", method = RequestMethod.GET)
	public String boardWriteForm(Model model) {
		List<BoardTypeBeans> typeList = boardTypeService.getAllBoardType();
		
		model.addAttribute("typeList", typeList);
		
		return "Board/board_write";
	}

	@RequestMapping(value = "/boardwrite", method = RequestMethod.POST)
	public String boardWrite(@ModelAttribute BoardBeans board,
			
			Model model,
			HttpSession session) {
		String sid = (String) session.getAttribute("sid");
		MemberBeans member = memberService.getMemberById(sid);

		board.setBoard_id(sid);
		board.setBoard_nickname(member.getMember_nickname());
		boardService.createBoard(board);
		
		int boardno = boardService.getMaxNo(sid);
				
		return "redirect:boardview?boardno=" + boardno;
	}

	@RequestMapping("/boardlist")
	public String boardList(HttpServletRequest request, Model model, HttpSession session) {
		System.out.println("리스트 호출");
		int pageno;
		String pagetype;

		try {
			pageno = Integer.parseInt(request.getParameter("pageno"));
			pagetype = request.getParameter("pagetype");
		} catch (Exception e) {
			pageno = 1;
			pagetype = "all";
		}

		int itemsPerPage = 10;
		int startNo = (pageno - 1) * itemsPerPage + 1;
		int endNo = pageno * itemsPerPage;

		HashMap<String, String> pageMap = new HashMap<String, String>();
		pageMap.put("startNo", Integer.toString(startNo));
		pageMap.put("endNo", Integer.toString(endNo));
		pageMap.put("type", pagetype);

		List<BoardBeans> boardList = null;

		if (pagetype.equals("all"))
			boardList = boardService.getAllBoard(pageMap);
		else
			boardList = boardService.getBoardByType(pageMap);

		model.addAttribute("boardList", boardList);

		int itemsPerLabel = 7;
		int totalPage;
		if (pagetype.equals("all")) {
			totalPage = boardService.getAllCount() / itemsPerPage;
			if (boardService.getAllCount() % itemsPerPage != 0)
				totalPage++;
		} else {
			totalPage = boardService.getCountByType(pagetype) / itemsPerPage;
			if (boardService.getCountByType(pagetype) % itemsPerPage != 0)
				totalPage++;
		}
		
		if(totalPage == 0) totalPage = 1;

		startNo = pageno - (itemsPerLabel / 2);
		if (startNo < 1)
			startNo = 1;

		endNo = startNo + itemsPerLabel - 1;
		if (endNo > totalPage)
			endNo = totalPage;

		startNo = endNo - itemsPerLabel + 1;
		if (startNo < 1)
			startNo = 1;

		String label = "";

		if (pageno == 1) {
			label += "<a style='color: black'>[처음 페이지]   </a>";
			label += "...   ";
			label += "<a style='color: black'>◀</a>";
		} else {
			label += "<a href='boardlist?pageno=1&pagetype=" + pagetype
					+ "'>[처음 페이지]   </a>";
			label += "...   ";
			label += "<a href='boardlist?pageno=" + (pageno - 1) + "&pagetype="
					+ pagetype + "'>◀ </a>";
		}

		for (int i = startNo; i <= endNo; i++) {
			if (pageno == i)
				label += "<a style='color: black'> " + i + " </a>";
			else
				label += "<a href='boardlist?pageno=" + i + "&pagetype="
						+ pagetype + "'> " + i + " </a>";
		}

		if (pageno == totalPage) {
			label += "<a style='color: black'>▶</a>";
			label += "   ...";
			label += "<a style='color: black'>   [마지막 페이지]</a>";
		} else {
			label += "<a href='boardlist?pageno=" + (pageno + 1) + "&pagetype="
					+ pagetype + "'>▶</a>";
			label += "   ...";
			label += "<a href='boardlist?pageno=" + totalPage + "&pagetype="
					+ pagetype + "'>   [마지막 페이지]</a>";
		}

		model.addAttribute("label", label);
		
		if((String)session.getAttribute("sid") != null) model.addAttribute("isLogin", true);		
		else model.addAttribute("isLogin", false);

		return "Board/board_list";
	}

	@RequestMapping("/boardview")
	public String boardDetailView(Model model, HttpServletRequest request,
			HttpSession session) {
		int boardno = Integer.parseInt(request.getParameter("boardno"));
		BoardBeans board = boardService.getBoardByNo(boardno);

		String content = board.getBoard_content();
		content.replaceAll("\n", "<br/>");
		board.setBoard_content(content);
		int show = board.getBoard_show();
		board.setBoard_show(show + 1);

		boardService.updateShow(boardno);

		model.addAttribute("board", board);

		List<BoardReplyBeans> reply = boardReplyService
				.getReplyByBoardNo(boardno);
		// for(BoardReplyBeans temp : reply){
		// temp.setBreply_nickname(memberService.getMemberById(temp.getBreply_id()).getMember_nickname());
		// }
		model.addAttribute("reply", reply);

		if (board.getBoard_id().equals((String) session.getAttribute("sid")))
			model.addAttribute("isSame", true);
		else
			model.addAttribute("isSame", false);
		
		if((String)session.getAttribute("sid") != null) model.addAttribute("isLogin", true);		
		else model.addAttribute("isLogin", false);		

		return "Board/board_detailView";
	}

	@RequestMapping(value = "/boardmodifyform", method = RequestMethod.POST)
	public String boardModifyForm(HttpServletRequest request, Model model) {
		int boardno = Integer.parseInt(request.getParameter("boardno"));
		BoardBeans board = boardService.getBoardByNo(boardno);
		List<BoardTypeBeans> typeList = boardTypeService.getAllBoardType();
		
		model.addAttribute("board", board);
		model.addAttribute("typeList", typeList);
		
		return "Board/board_modify";
	}

	@RequestMapping(value = "/boardmodify", method = RequestMethod.POST)
	public String boardModify(@ModelAttribute BoardBeans board) {
		boardService.updateBoard(board);

		return "redirect:boardview?boardno=" + board.getBoard_no();
	}

	@RequestMapping("/boarddelete")
	public String deleteBoard(HttpServletRequest request, Model model) {
		System.out.println("게시물 삭제");

		boardService.deleteBoard(Integer.parseInt(request
				.getParameter("boardno")));

		return "redirect:boardlist?pageno=1&pagetype=all";
	}

	@RequestMapping("/replyWrite")
	public @ResponseBody List<BoardReplyBeans> replyWrite(
			@RequestParam(value = "boardno") int boardno,
			@RequestParam(value = "content") String content,
			HttpSession session) {
		BoardReplyBeans reply = new BoardReplyBeans(0, boardno, null, (String) session.getAttribute("sid"), 0, content);
		boardReplyService.createReply(reply);

		List<BoardReplyBeans> replyBeans = boardReplyService.getReplyByBoardNo(boardno);

		return replyBeans;
	}

	@RequestMapping("/replyRecommend")
	public @ResponseBody String replyRecommend(
			@RequestParam(value = "boardno") int boardno,
			@RequestParam(value = "replyno") int replyno,
			HttpSession session) {
		boardReplyService.updateRecommend(replyno);

		List<BoardReplyBeans> replyBeans = boardReplyService.getReplyByBoardNo(boardno);
		
		BoardReplyBeans reply = new BoardReplyBeans();
		for(BoardReplyBeans temp : replyBeans){
			if(temp.getBreply_no() == replyno) reply = temp;
		}

		return Integer.toString(reply.getBreply_recommend());
	}
	
	@RequestMapping("/boardRecommend")
	public @ResponseBody String boardRecommend(
			@RequestParam(value = "boardno") int boardno) {
		boardService.updateRecommend(boardno);
		
		return Integer.toString(boardService.getBoardByNo(boardno).getBoard_recommend());
	}
}